#include <cassert>
#include <iostream>
#include <fstream>   // file I/O
#include <sstream> // stringstream
#include <cstdlib>
#include <math.h>
#include "pgm.h"
using namespace std;




/***********************************
 * CONSTRUCTORES ******************
 *********************************/

PGM::PGM(const char *filename){
    int row = 0, col = 0, numrows = 0, numcols = 0, maxVal = 0;
  	ifstream infile(filename, ios::binary);
  	stringstream ss;
  	string inputLine = "";

  	// First line : version
  	//getline(infile,inputLine);
	//infile.get(inputLine);
  	//cout << "Version : " << inputLine << endl;

  	/*// Second line : comment
  	getline(infile,inputLine);
  	cout << "Comment : " << inputLine << endl;*/

  	// Continue with a stringstream
  	ss << infile.rdbuf();
  	// Third line : size
  	ss >> inputLine >> numcols >> numrows >> maxVal;
  	cout << numcols << " columns and " << numrows << " rows" << endl;
	this->data = new unsigned short[numcols*numrows];
  	//int array[numrows][numcols];
	unsigned char temp;
  	// Following lines : data
  	for(row = 0; row < numrows; ++row)
  	  for (col = 0; col < numcols; ++col){
		 ss >> temp;
		 this->data[row*numcols + col] = (unsigned short) temp;
	  }

  	// Now print the array to see the result
  	for(row = 0; row < numrows; ++row) {
  	  for(col = 0; col < numcols; ++col) {
  	    //cout << this->data[row*numcols + col] << " ";
  	  }
  	  //cout << endl;
  	}
  	infile.close();
	//this->data = array;
	this->width = numcols;
	this->height = numrows;
}

int PGM::getPixel(int i, int j){
	int pixel = i*this->width + j;
	int res = this->data[pixel];
	return res;
}

unsigned short* PGM::getData(){
	return this->data;
}



